package 数据结构.章节09._145_基于数组实现线性表;

/**
 * @author 挚爱之夕
 * @date 2021/10/5 - 10 - 05 - 16:06
 * @Description: 数据结构.章节09
 * @Version: 1.0
 */

/*
用顺序储存
 */
public class MyArrayList<T> implements MyList<T>{
    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public T next() {
        return null;
    }

    /*底层储存结构*/
    private T[] elements;
    /*当前包含的元素个数*/
    private int size = 0;
    /*最大容量*/
    private int capacity = 10;
    /*构造方法，建立储存结构*/
    public MyArrayList(int capacity) {
        this.capacity = capacity;
        elements = (T[]) new Object[capacity];
    }

    public MyArrayList() {
        elements = (T[]) new Object[capacity];
    }
    @Override
    public void add(T o) {
        if(size == capacity){   /*容量不够，扩容*/
            capacity *= 2;
            T[] newElements = (T[]) new Object[capacity];
            for (int i = 0; i < size; i++) {
                newElements[i] = elements[i];
            }
            elements = newElements;
        }
        elements[size++] = o;
    }

    @Override
    public void delete(T o) {
        int index = find(o);
        if(index>=0){
            delete(index);
        }
    }

    @Override
    public void delete(int index) {
        for (int i = index; i < size; i++) {
            elements[i] = elements[i+1];
        }
        elements[size-1] = null;
        size -=1;   //当前包含元素减一
    }

    @Override
    public void modify(int index, T o) {
        elements[index] = o;
    }

    @Override
    public boolean contains(T o) {
        int index = find(o);
        return index>=0;
    }

    @Override
    public int find(T o) {
        for (int i = 0; i < size; i++) {
            if(elements[i].equals(o))
                return i;
        }
        return -1;
    }

    @Override
    public T find(int index) {
        return elements[index];
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            sb.append(elements[i]).append(i == size - 1 ? "" : " ,");
        }
        sb.append("]");
        return sb.toString();
    }
}
